/**
 * @(#) EventManager.java
 */

package edu.stthomas.edu.seis770.stocksystem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

public class EventManager implements Observer {
    public static final String STOCK_UPDATE_EVENT = "update";
    public static final String STOCK_CREATE_EVENT = "create";


    private static EventManager uniqueInstance = null;

    private Map<String, List<EventSubscriber>> eventsSubscribersMap;

    protected EventManager() {
        eventsSubscribersMap = new HashMap<String, List<EventSubscriber>>();
    }

    public static EventManager getUniqueInstance() {
        if(uniqueInstance == null){
            uniqueInstance = new EventManager();
        }
        return uniqueInstance;
    }

    public void update(Observable observable, Object object) {
        if(object instanceof String){
            String event = (String) object;
            notify(observable, event);
        }

    }

    public void register(EventSubscriber subscriber, List<String> events) {
        for(String event: events){
            if(eventsSubscribersMap.containsKey(event)){
                List<EventSubscriber> subscribers = eventsSubscribersMap.get(event);
                subscribers.add(subscriber);
            }
            // this means no one registered for this event yet
            else{
                List<EventSubscriber> subscribers = new ArrayList<EventSubscriber>();
                subscribers.add(subscriber);
                eventsSubscribersMap.put(event, subscribers);
            }
        }
    }

    private void notify(Object subject, String event) {
        if(eventsSubscribersMap.containsKey(event)){
            List<EventSubscriber> subscribers = eventsSubscribersMap.get(event);
            for(EventSubscriber subscriber: subscribers){
                subscriber.update(subject, event);
            }
        }

    }


}
